const errorHandler = async (ctx, next) => {
  try {
    await next()
    // 成功响应统一格式化
    // 是否swagger
    if (ctx.path.startsWith('/swagger')) {
      return
    } else {
      if (ctx.body && !ctx.body.error) {
        ctx.body = {
          success: true,
          data: ctx.body,
          timestamp: new Date().toLocaleString(),
          requestId: ctx.state.requestId,
        }
      }
    }
  } catch (err) {
    // 错误响应结构
    const response = {
      success: false,
      error: {
        type: err.name || 'InternalError',
        code: err.code || 500,
        message: err.message,
        details: err.details || undefined,
        stack: process.env.NODE_ENV === 'development' ? err.stack : undefined,
      },
      timestamp: new Date().toLocaleString(),
      requestId: ctx.state.requestId,
    }

    ctx.status = response.error.code
    ctx.body = response

    // 触发错误日志
    ctx.app.emit('error', err, ctx)
  }
}
module.exports = errorHandler
